﻿using IntelligentGateway.Tools;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentGateway.Services
{
    public class SerialPortServer
    {
        SerialPort _sp;
        public SerialPortServer(string StrPortName, string StrBaudRate, string StrDataBits, string StrParity, string StrStopBits)
        {
            int iBaudRate = int.Parse(StrBaudRate);
            int iDataBits = int.Parse(StrDataBits);
            Parity parity =
                string.IsNullOrEmpty(StrParity) ? System.IO.Ports.Parity.None :
                StrParity.Equals("ODD") ? System.IO.Ports.Parity.Odd :
                StrParity.Equals("EVEN") ? System.IO.Ports.Parity.Even :
                StrParity.Equals("MARK") ? System.IO.Ports.Parity.Mark : StrParity.Equals("NONE") ? System.IO.Ports.Parity.None : System.IO.Ports.Parity.Space;
            StopBits stopBits
                = string.IsNullOrEmpty(StrStopBits) ? System.IO.Ports.StopBits.None :
                StrStopBits.Equals("1") ? System.IO.Ports.StopBits.One :
                StrStopBits.Equals("1.5") ? System.IO.Ports.StopBits.OnePointFive : System.IO.Ports.StopBits.Two;
            this._sp = new SerialPort(StrPortName, iBaudRate, parity, iDataBits, stopBits);           
        }
        public bool Open()
        {
            try
            {
                this._sp.Open();
                return true;
            }
            catch (Exception e)
            {
                Log.Debug("open serial is error!" + e.ToString());
                return false;
            }
        }
        public SerialPort SerialPort
        {
            get { return _sp; }
        }
    }
}
